<script setup lang="ts">
import type {
  AlertRule,
  Metric,
  MonitoringFacet,
} from '#/api/resource-center/types';

import { computed, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

// Props
interface Props {
  monitoring?: MonitoringFacet;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  update: [monitoring: MonitoringFacet];
}>();

// 响应式数据
const metricModalVisible = ref(false);
const alertModalVisible = ref(false);
const dashboardModalVisible = ref(false);
const editingMetric = ref<Metric | null>(null);
const editingAlert = ref<AlertRule | null>(null);

// 表单数据
const metricForm = reactive({
  name: '',
  type: 'GAUGE',
  description: '',
  unit: '',
  interval: '60s',
  thresholds: [] as any[],
});

const alertForm = reactive({
  name: '',
  severity: 'MEDIUM',
  condition: '',
  duration: '5m',
  evaluationInterval: '1m',
  message: '',
  actions: [] as any[],
});

// 计算属性
const monitoring = computed(
  () =>
    props.monitoring || {
      metrics: [],
      alerts: [],
    },
);

const activeAlertsCount = computed(
  () =>
    monitoring.value.alerts?.filter((alert) => alert.status === 'FIRING')
      .length || 0,
);

const availability = computed(() => {
  // 模拟可用性计算
  return 99.5;
});

// 监控面板数据
const alertStatusColumns = [
  { title: '告警名称', dataIndex: 'name', key: 'name' },
  { title: '严重程度', dataIndex: 'severity', key: 'severity' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '持续时间', dataIndex: 'duration', key: 'duration' },
];

const alertStatusData = [
  {
    name: 'CPU使用率过高',
    severity: 'HIGH',
    status: 'FIRING',
    duration: '10m',
  },
  {
    name: '内存使用率过高',
    severity: 'MEDIUM',
    status: 'RESOLVED',
    duration: '5m',
  },
];

// 方法
const getMetricTypeColor = (type?: string) => {
  const colorMap: Record<string, string> = {
    COUNTER: 'blue',
    GAUGE: 'green',
    HISTOGRAM: 'purple',
    SUMMARY: 'orange',
  };
  return colorMap[type || ''] || 'default';
};

const getMetricTypeLabel = (type?: string) => {
  const labelMap: Record<string, string> = {
    COUNTER: '计数器',
    GAUGE: '仪表盘',
    HISTOGRAM: '直方图',
    SUMMARY: '摘要',
  };
  return labelMap[type || ''] || type || '未知';
};

const getAlertSeverityColor = (severity?: string) => {
  const colorMap: Record<string, string> = {
    LOW: 'green',
    MEDIUM: 'orange',
    HIGH: 'red',
    CRITICAL: 'red',
  };
  return colorMap[severity || ''] || 'default';
};

const getAlertSeverityLabel = (severity?: string) => {
  const labelMap: Record<string, string> = {
    LOW: '低',
    MEDIUM: '中',
    HIGH: '高',
    CRITICAL: '严重',
  };
  return labelMap[severity || ''] || severity || '未知';
};

const getAlertStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    ENABLED: 'green',
    DISABLED: 'gray',
    FIRING: 'red',
    RESOLVED: 'blue',
  };
  return colorMap[status || ''] || 'default';
};

const getAlertStatusLabel = (status?: string) => {
  const labelMap: Record<string, string> = {
    ENABLED: '启用',
    DISABLED: '禁用',
    FIRING: '告警中',
    RESOLVED: '已解决',
  };
  return labelMap[status || ''] || status || '未知';
};

const formatThresholds = (thresholds: any[]) => {
  return thresholds
    .map((t) => `${t.level}: ${t.operator} ${t.value}`)
    .join(', ');
};

// 指标管理方法
const showAddMetricModal = () => {
  editingMetric.value = null;
  resetMetricForm();
  metricModalVisible.value = true;
};

const editMetric = (metric: Metric) => {
  editingMetric.value = metric;
  metricForm.name = metric.name;
  metricForm.type = metric.type;
  metricForm.description = metric.description || '';
  metricForm.unit = metric.unit || '';
  metricForm.interval = metric.interval || '60s';
  metricForm.thresholds = [...(metric.thresholds || [])];
  metricModalVisible.value = true;
};

const saveMetric = () => {
  if (!metricForm.name || !metricForm.description) {
    message.error('请填写指标名称和描述');
    return;
  }

  const newMetric: Metric = {
    name: metricForm.name,
    type: metricForm.type,
    description: metricForm.description,
    unit: metricForm.unit,
    interval: metricForm.interval,
    thresholds: metricForm.thresholds,
  };

  const currentMetrics = monitoring.value.metrics || [];
  let newMetrics: Metric[];
  newMetrics;

  newMetrics = editingMetric.value
    ? currentMetrics.map((m) =>
        m.name === editingMetric.value!.name ? newMetric : m,
      )
    : [...currentMetrics, newMetric];

  emit('update', { ...monitoring.value, metrics: newMetrics });
  message.success(editingMetric.value ? '指标更新成功' : '指标添加成功');
  metricModalVisible.value = false;
  resetMetricForm();
};

const cancelMetric = () => {
  metricModalVisible.value = false;
  resetMetricForm();
};

const resetMetricForm = () => {
  metricForm.name = '';
  metricForm.type = 'GAUGE';
  metricForm.description = '';
  metricForm.unit = '';
  metricForm.interval = '60s';
  metricForm.thresholds = [];
};

const deleteMetric = (metricName: string) => {
  const newMetrics =
    monitoring.value.metrics?.filter((m) => m.name !== metricName) || [];
  emit('update', { ...monitoring.value, metrics: newMetrics });
  message.success('指标删除成功');
};

const viewMetricChart = (metric: Metric) => {
  message.info(`查看指标图表: ${metric.name}`);
};

// 阈值编辑器方法
const addThreshold = () => {
  metricForm.thresholds.push({
    level: 'WARNING',
    operator: 'GT',
    value: '',
  });
};

const removeThreshold = (index: number) => {
  metricForm.thresholds.splice(index, 1);
};

// 告警管理方法
const showAddAlertModal = () => {
  editingAlert.value = null;
  resetAlertForm();
  alertModalVisible.value = true;
};

const editAlert = (alert: AlertRule) => {
  editingAlert.value = alert;
  alertForm.name = alert.name;
  alertForm.severity = alert.severity;
  alertForm.condition = alert.condition;
  alertForm.duration = alert.duration || '5m';
  alertForm.evaluationInterval = alert.evaluationInterval || '1m';
  alertForm.message = alert.message || '';
  alertForm.actions = [...(alert.actions || [])];
  alertModalVisible.value = true;
};

const saveAlert = () => {
  if (!alertForm.name || !alertForm.condition) {
    message.error('请填写告警名称和条件');
    return;
  }

  const newAlert: AlertRule = {
    id: editingAlert.value?.id || `alert_${Date.now()}`,
    name: alertForm.name,
    severity: alertForm.severity,
    condition: alertForm.condition,
    duration: alertForm.duration,
    evaluationInterval: alertForm.evaluationInterval,
    message: alertForm.message,
    actions: alertForm.actions,
    status: 'ENABLED',
  };

  const currentAlerts = monitoring.value.alerts || [];
  let newAlerts: AlertRule[];
  newAlerts;

  newAlerts = editingAlert.value
    ? currentAlerts.map((a) => (a.id === editingAlert.value!.id ? newAlert : a))
    : [...currentAlerts, newAlert];

  emit('update', { ...monitoring.value, alerts: newAlerts });
  message.success(editingAlert.value ? '告警更新成功' : '告警添加成功');
  alertModalVisible.value = false;
  resetAlertForm();
};

const cancelAlert = () => {
  alertModalVisible.value = false;
  resetAlertForm();
};

const resetAlertForm = () => {
  alertForm.name = '';
  alertForm.severity = 'MEDIUM';
  alertForm.condition = '';
  alertForm.duration = '5m';
  alertForm.evaluationInterval = '1m';
  alertForm.message = '';
  alertForm.actions = [];
};

const deleteAlert = (alertId: string) => {
  const newAlerts =
    monitoring.value.alerts?.filter((a) => a.id !== alertId) || [];
  emit('update', { ...monitoring.value, alerts: newAlerts });
  message.success('告警删除成功');
};

const toggleAlert = (alertId: string, enabled: boolean) => {
  const newAlerts =
    monitoring.value.alerts?.map((a) =>
      a.id === alertId ? { ...a, status: enabled ? 'ENABLED' : 'DISABLED' } : a,
    ) || [];
  emit('update', { ...monitoring.value, alerts: newAlerts });
  message.success(`告警${enabled ? '启用' : '禁用'}成功`);
};

// 动作编辑器方法
const addAction = () => {
  alertForm.actions.push({
    type: 'EMAIL',
    target: '',
  });
};

const removeAction = (index: number) => {
  alertForm.actions.splice(index, 1);
};

// 监控面板方法
const showMonitoringDashboard = () => {
  dashboardModalVisible.value = true;
};
</script>

<template>
  <div class="resource-monitoring">
    <!-- 监控管理头部 -->
    <div class="monitoring-header">
      <h3>监控管理</h3>
      <a-space>
        <a-button type="primary" @click="showAddAlertModal">
          <template #icon>
            <IconifyIcon icon="ant-design:plus-outlined" />
          </template>
          添加告警
        </a-button>
        <a-button @click="showMonitoringDashboard">
          <template #icon>
            <DashboardOutlined />
          </template>
          监控面板
        </a-button>
      </a-space>
    </div>

    <!-- 监控概览 -->
    <a-card title="监控概览" class="monitoring-card">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-statistic
            title="监控指标"
            :value="monitoring?.metrics?.length || 0"
          />
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="告警规则"
            :value="monitoring?.alerts?.length || 0"
          />
        </a-col>
        <a-col :span="6">
          <a-statistic title="活跃告警" :value="activeAlertsCount" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="可用性" :value="availability" suffix="%" />
        </a-col>
      </a-row>
    </a-card>

    <!-- 监控指标 -->
    <a-card title="监控指标" class="monitoring-card">
      <div class="metrics-section">
        <a-button @click="showAddMetricModal" type="dashed" block>
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加指标
        </a-button>

        <div v-if="monitoring?.metrics?.length" class="metrics-list">
          <a-card
            v-for="metric in monitoring.metrics"
            :key="metric.name"
            class="metric-card"
            size="small"
          >
            <template #title>
              <div class="metric-title">
                <span>{{ metric.name }}</span>
                <a-tag :color="getMetricTypeColor(metric.type)" size="small">
                  {{ getMetricTypeLabel(metric.type) }}
                </a-tag>
              </div>
            </template>

            <div class="metric-info">
              <p><strong>描述:</strong> {{ metric.description }}</p>
              <p><strong>单位:</strong> {{ metric.unit || '无' }}</p>
              <p><strong>采集间隔:</strong> {{ metric.interval || '60s' }}</p>
              <p v-if="metric.thresholds">
                <strong>阈值:</strong> {{ formatThresholds(metric.thresholds) }}
              </p>
            </div>

            <div class="metric-actions">
              <a-button type="link" size="small" @click="editMetric(metric)">
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                @click="viewMetricChart(metric)"
              >
                图表
              </a-button>
              <a-popconfirm
                title="确定要删除这个指标吗？"
                @confirm="deleteMetric(metric.name)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </div>
          </a-card>
        </div>
      </div>
    </a-card>

    <!-- 告警规则 -->
    <a-card title="告警规则" class="monitoring-card">
      <div class="alerts-section">
        <a-empty
          v-if="!monitoring?.alerts?.length"
          description="暂无告警规则"
        />

        <div v-else class="alerts-list">
          <a-card
            v-for="alert in monitoring.alerts"
            :key="alert.id"
            class="alert-card"
            size="small"
          >
            <template #title>
              <div class="alert-title">
                <span>{{ alert.name }}</span>
                <a-tag
                  :color="getAlertSeverityColor(alert.severity)"
                  size="small"
                >
                  {{ getAlertSeverityLabel(alert.severity) }}
                </a-tag>
              </div>
            </template>

            <div class="alert-info">
              <p><strong>条件:</strong> {{ alert.condition }}</p>
              <p><strong>持续时间:</strong> {{ alert.duration || '1m' }}</p>
              <p>
                <strong>状态:</strong>
                <a-tag :color="getAlertStatusColor(alert.status)">
                  {{ getAlertStatusLabel(alert.status) }}
                </a-tag>
              </p>
            </div>

            <div class="alert-actions">
              <a-button type="link" size="small" @click="editAlert(alert)">
                编辑
              </a-button>
              <a-button
                v-if="alert.status === 'ENABLED'"
                type="link"
                size="small"
                @click="toggleAlert(alert.id, false)"
              >
                禁用
              </a-button>
              <a-button
                v-else
                type="link"
                size="small"
                @click="toggleAlert(alert.id, true)"
              >
                启用
              </a-button>
              <a-popconfirm
                title="确定要删除这个告警规则吗？"
                @confirm="deleteAlert(alert.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </div>
          </a-card>
        </div>
      </div>
    </a-card>

    <!-- 添加指标模态框 -->
    <a-modal
      v-model:open="metricModalVisible"
      :title="editingMetric ? '编辑指标' : '添加指标'"
      width="600px"
      @ok="saveMetric"
      @cancel="cancelMetric"
    >
      <a-form :model="metricForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="指标名称" name="name">
              <a-input
                v-model:value="metricForm.name"
                placeholder="请输入指标名称"
                :disabled="!!editingMetric"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="指标类型" name="type">
              <a-select
                v-model:value="metricForm.type"
                placeholder="请选择指标类型"
              >
                <a-select-option value="COUNTER">计数器</a-select-option>
                <a-select-option value="GAUGE">仪表盘</a-select-option>
                <a-select-option value="HISTOGRAM">直方图</a-select-option>
                <a-select-option value="SUMMARY">摘要</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="metricForm.description"
            placeholder="请输入指标描述"
            :rows="3"
          />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="单位" name="unit">
              <a-input
                v-model:value="metricForm.unit"
                placeholder="请输入单位"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="采集间隔" name="interval">
              <a-input
                v-model:value="metricForm.interval"
                placeholder="如：60s"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="阈值配置" name="thresholds">
          <div class="thresholds-editor">
            <a-button @click="addThreshold" type="dashed" block>
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加阈值
            </a-button>

            <div v-if="metricForm.thresholds" class="thresholds-list">
              <div
                v-for="(threshold, index) in metricForm.thresholds"
                :key="index"
                class="threshold-item"
              >
                <a-row :gutter="8">
                  <a-col :span="6">
                    <a-select
                      v-model:value="threshold.level"
                      placeholder="级别"
                    >
                      <a-select-option value="WARNING">警告</a-select-option>
                      <a-select-option value="CRITICAL">严重</a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="6">
                    <a-select
                      v-model:value="threshold.operator"
                      placeholder="操作符"
                    >
                      <a-select-option value="GT">大于</a-select-option>
                      <a-select-option value="LT">小于</a-select-option>
                      <a-select-option value="EQ">等于</a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="8">
                    <a-input
                      v-model:value="threshold.value"
                      placeholder="阈值"
                    />
                  </a-col>
                  <a-col :span="4">
                    <a-button
                      type="text"
                      danger
                      @click="removeThreshold(index)"
                    >
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </a-button>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 添加告警模态框 -->
    <a-modal
      v-model:open="alertModalVisible"
      :title="editingAlert ? '编辑告警' : '添加告警'"
      width="700px"
      @ok="saveAlert"
      @cancel="cancelAlert"
    >
      <a-form :model="alertForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="告警名称" name="name">
              <a-input
                v-model:value="alertForm.name"
                placeholder="请输入告警名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="严重程度" name="severity">
              <a-select
                v-model:value="alertForm.severity"
                placeholder="请选择严重程度"
              >
                <a-select-option value="LOW">低</a-select-option>
                <a-select-option value="MEDIUM">中</a-select-option>
                <a-select-option value="HIGH">高</a-select-option>
                <a-select-option value="CRITICAL">严重</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="告警条件" name="condition">
          <a-textarea
            v-model:value="alertForm.condition"
            placeholder="请输入告警条件（如：cpu_usage > 80）"
            :rows="3"
          />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="持续时间" name="duration">
              <a-input
                v-model:value="alertForm.duration"
                placeholder="如：5m"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="评估间隔" name="evaluationInterval">
              <a-input
                v-model:value="alertForm.evaluationInterval"
                placeholder="如：1m"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="告警动作" name="actions">
          <div class="actions-editor">
            <a-button @click="addAction" type="dashed" block>
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加动作
            </a-button>

            <div v-if="alertForm.actions" class="actions-list">
              <div
                v-for="(action, index) in alertForm.actions"
                :key="index"
                class="action-item"
              >
                <a-row :gutter="8">
                  <a-col :span="6">
                    <a-select
                      v-model:value="action.type"
                      placeholder="动作类型"
                    >
                      <a-select-option value="EMAIL">邮件</a-select-option>
                      <a-select-option value="SMS">短信</a-select-option>
                      <a-select-option value="WEBHOOK">Webhook</a-select-option>
                      <a-select-option value="SLACK">Slack</a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="12">
                    <a-input
                      v-model:value="action.target"
                      placeholder="目标地址"
                    />
                  </a-col>
                  <a-col :span="4">
                    <a-button type="text" danger @click="removeAction(index)">
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </a-button>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </a-form-item>

        <a-form-item label="告警消息" name="message">
          <a-textarea
            v-model:value="alertForm.message"
            placeholder="请输入告警消息模板"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 监控面板模态框 -->
    <a-modal
      v-model:open="dashboardModalVisible"
      title="监控面板"
      width="1200px"
      :footer="null"
    >
      <div class="monitoring-dashboard">
        <a-alert
          message="监控面板功能"
          description="这里将展示实时监控数据、图表和告警状态。"
          type="info"
          show-icon
          style="margin-bottom: 16px"
        />

        <a-row :gutter="16">
          <a-col :span="12">
            <a-card title="CPU使用率" size="small">
              <div class="chart-placeholder">
                <a-progress type="circle" :percent="75" />
                <p>75%</p>
              </div>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card title="内存使用率" size="small">
              <div class="chart-placeholder">
                <a-progress type="circle" :percent="60" />
                <p>60%</p>
              </div>
            </a-card>
          </a-col>
        </a-row>

        <a-card title="告警状态" size="small" style="margin-top: 16px">
          <a-table
            :columns="alertStatusColumns"
            :data-source="alertStatusData"
            :pagination="false"
            size="small"
          />
        </a-card>
      </div>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.resource-monitoring {
  .monitoring-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
    }
  }

  .monitoring-card {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .metrics-section {
    .metrics-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
      gap: 12px;
      margin-top: 12px;
    }

    .metric-card {
      .metric-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .metric-info {
        margin-bottom: 8px;

        p {
          margin: 4px 0;
          font-size: 12px;
        }
      }

      .metric-actions {
        display: flex;
        gap: 4px;
      }
    }
  }

  .alerts-section {
    .alerts-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
      gap: 12px;
    }

    .alert-card {
      .alert-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .alert-info {
        margin-bottom: 8px;

        p {
          margin: 4px 0;
          font-size: 12px;
        }
      }

      .alert-actions {
        display: flex;
        gap: 4px;
      }
    }
  }

  .thresholds-editor,
  .actions-editor {
    .thresholds-list,
    .actions-list {
      margin-top: 12px;

      .threshold-item,
      .action-item {
        margin-bottom: 8px;
        padding: 8px;
        border: 1px solid #f0f0f0;
        border-radius: 4px;
        background: #fafafa;
      }
    }
  }

  .monitoring-dashboard {
    .chart-placeholder {
      text-align: center;
      padding: 20px;

      p {
        margin-top: 8px;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
}
</style>
